  import * as http from '@/utils/http'  
  import {
    useUserInfo
  } from '@/stores/userinfo.js';
  
  const userInfo=useUserInfo()
  
  async function prepay(channel,id) {
    let data = {
      id,
      channelCode: channel,
      channelExtras: {}
    }
    // 特殊逻辑：微信公众号、小程序支付时，必须传入 openid
    if (['wx_pub', 'wx_lite'].includes(channel)) {
      const openid = userInfo.loginData.openid
      // 如果获取不到 openid，微信无法发起支付，此时需要引导
      data.channelExtras.openid = openid;
    }
    // 发起预支付 API 调用
    const result = await http.postRequest("/pay/order/submit", data)
    return result
  }
  
  // 微信小程序支付
  async function wechatMiniProgramPay(id) {
    let {
      code,
      data
    } = await prepay('wx_lite',id);
    if (code !== 0) {
      return;
    }
    // 调用微信小程序支付
    const payConfig = JSON.parse(data.displayContent);
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: payConfig.timeStamp,
      nonceStr: payConfig.nonceStr,
      package: payConfig.packageValue,
      signType: payConfig.signType,
      paySign: payConfig.paySign,
      success: (res) => {
      uni.switchTab({
        url: '/pages/order/index'
      });
      },
      fail: (err) => {
        if (err.errMsg === 'requestPayment:fail cancel') {
          uni.showToast({
            title: '支付已手动取消',
            icon: 'error',
            duration: 1000
          })
        } else {
          uni.showToast({
            title: '支付异常',
            icon: 'error',
            duration: 1000
          })
        }
      },
    });
  }
  
  export default wechatMiniProgramPay